import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from 'react';
import {formatRelativeTime} from '@/utils/timeUtils';
import {deviceApi, EquipmentAlarm} from '@/services/api/deviceApi';
import {formatMinutesToTimeUnit} from '@/utils';
import dayjs from 'dayjs';
import {DeviceApiDataTypes} from '@/store/slices/deviceSlice';
import {DeviceType} from '@/services/api/deviceApi';
// 设备信息上下文类型定义
export type DeviceInfoContextType = DeviceApiDataTypes & {
  errors: EquipmentAlarm[];
  state: {
    isConnect: boolean;
    lastTime: string;
    workTime: string;
    isToday: boolean;
  };
};

// 创建上下文
const DeviceInfoContext = createContext<DeviceInfoContextType | undefined>(
  undefined,
);

// Provider组件
interface DeviceInfoProviderProps {
  children: ReactNode;
  initialDeviceData?: (DeviceApiDataTypes & {deviceType: DeviceType}) | null;
}

export const DeviceInfoProvider: React.FC<DeviceInfoProviderProps> = ({
  children,
  initialDeviceData: deviceData,
}) => {
  const [errors, setErrors] = useState<EquipmentAlarm[]>([]);
  const isToday = dayjs(deviceData?.lastUpdateTime ?? '').isValid()
    ? dayjs(deviceData?.lastUpdateTime).isSame(dayjs(), 'day')
    : false;
  // 计算属性
  const lastTime = formatRelativeTime(deviceData?.lastUpdateTime!);
  const isConnect = (deviceData?.devStatus ?? 'offline') !== 'offline';
  const workTime = formatMinutesToTimeUnit(deviceData?.runTime ?? 0);

  // 初始化获取告警信息
  useEffect(() => {
    const fetchAlarms = async () => {
      if (deviceData?.alarmNum! > 0 && deviceData?.sn) {
        try {
          const {data} = await deviceApi.getAlarmList({
            deviceSn: deviceData.sn,
            deviceType: deviceData.deviceType,
          });
          setErrors(data.records);
        } catch (error) {
          console.error('获取告警信息失败:', error);
        }
      }
    };
    fetchAlarms();
  }, [deviceData?.alarmNum, deviceData?.sn, deviceData?.deviceType]);

  const contextValue: DeviceInfoContextType = {
    state: {
      lastTime,
      workTime,
      isConnect,
      isToday,
    },
    ...deviceData!,
    errors,
  };

  return (
    <DeviceInfoContext.Provider value={contextValue}>
      {children}
    </DeviceInfoContext.Provider>
  );
};

// Hook 用于使用上下文
export const useDeviceInfo = () => {
  const context = useContext(DeviceInfoContext);

  if (!context) {
    throw new Error('useDeviceInfo must be used within a DeviceInfoProvider');
  }
  return context;
};
